package com.kevin.controller;

import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

public class ServletContextInitializer extends HttpServlet implements Runnable {
    private static final long serialVersionUID = -6517837241755564982L;
    public static String fileName;
	public static final String DEFAULT_FILENAME="servletContext.properties";

	@Override
	public void init() throws ServletException {
		fileName = getInitParameter("fileName");
		String reloadable = getInitParameter("reloadable");
		if(fileName==null){
			fileName=DEFAULT_FILENAME;
		}
		if(reloadable==null){
		    reloadable="false";
		}
		if(Boolean.parseBoolean(reloadable)){
		    Thread t=new Thread(this);
		    t.start();
		}else{
		    loadProp();
		}
	}
	
	private void loadProp(){    
		try {
		    Properties prop=new Properties();
			prop.load(getClass().getClassLoader().getResourceAsStream(fileName));
			Set<Entry<Object, Object>> entrySet = prop.entrySet();
	        ServletContext servletContext = getServletContext();
	        for(Entry<Object, Object> entry:entrySet){
	            servletContext.setAttribute(entry.getKey().toString(), entry.getValue());
	        }
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	


    public void run() {
        while(true){
            loadProp();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
